package AdminService

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
	"time"
)

const adminModelCacheTempetle = "adminCache:%s:model"

func Person(ctx context.Context, req *BaseReq.I) *response.JsonResponse {
	cacheAdminId := gconv.String(req.AdminId)
	cfgTmp, _ := g.Cfg().Get(ctx, "site.AdminCacheTimeout", 600)
	cacheDuration := cfgTmp.Duration() * time.Second
	obj := db.GetUnSafaTable(ctx, "admin").Handler(db.SoftDeleteHandler).WherePri(
		"id",
		req.AdminId,
	)
	// 过滤字段
	if len(req.InfoIgnoreProperty) > 0 {
		obj.Fields(obj.GetFieldsExStr(req.InfoIgnoreProperty))
	}
	res, err := obj.Cache(gdb.CacheOption{
		//Name:     "adminCache:" + cacheAdminId + ":model",
		Name:     fmt.Sprintf(adminModelCacheTempetle, cacheAdminId),
		Duration: cacheDuration,
	}).One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	if res.IsEmpty() {
		return response.FailByRequestMessage(nil, "获取信息失败")
	}
	result := res.Map()
	// 删除敏感信息
	delete(result, "password")
	delete(result, "password_salt")
	// 取部门
	resCon, err := db.GetUnSafaTable(ctx, "sys_department").Handler(db.SoftDeleteHandler).Where(
		"id",
		result["dept_id"],
	).Fields("name").Cache(gdb.CacheOption{
		Name:     "adminCache:" + cacheAdminId + ":depaName",
		Duration: cacheDuration,
	}).Value()
	result["departmentName"] = resCon.String()
	// 取角色
	roleIds, err := db.GetUnSafaTable(ctx, "admin_role").Where(
		"admin_id",
		result["id"],
	).Fields("role_id").Cache(gdb.CacheOption{
		Name:     "adminCache:" + cacheAdminId + ":roleIdList",
		Duration: cacheDuration,
	}).Array()
	result["roleIdList"] = gconv.SliceInt(roleIds)
	PhotoPreFixTmp, err := g.Cfg().Get(ctx, "upload.PhotoPreFix", "")
	if err == nil {
		result["avatar_profix"] = PhotoPreFixTmp.String()
	}
	return response.SuccessByRequestMessageData(nil, "获取成功",
		result)
}
